package com.software.chemistry.service.Impl;

import com.software.chemistry.entity.ModelMine;
import com.software.chemistry.repository.ModelMineRepository;
import com.software.chemistry.service.ModelMineService;
import com.software.chemistry.util.FormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 *
 */
@Service
@Transactional
public class ModelMineServiceImpl implements ModelMineService {

    @Autowired
    private ModelMineRepository modelMineRepository;

    public List<ModelMine> ListModelMineById(String userId){
        return modelMineRepository.ListModelMineById(userId);
    }

    @Override
    public void saveModelMine(String file) {
        file = FormatUtil.hexStringToString(file);

        Path rootLocation = Paths.get("model");
        if(Files.notExists(rootLocation)){
            try {
                Files.createDirectories(rootLocation);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Path path = rootLocation.resolve("123.fbx");
        byte[] strToBytes = file.getBytes();
        try {
            Files.write(path, strToBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("成功保存文件");

        int id = modelMineRepository.getCount("2c3d51b3-0f50-4d00-925e-e48c5566e174") + 1;
        FormatUtil.FbxToObj("123.fbx", String.valueOf(id));

        ModelMine modelMine = new ModelMine();
        modelMine.setUserId("2c3d51b3-0f50-4d00-925e-e48c5566e174");
        modelMine.setModelName("新模型");
        modelMine.setModelId(id + "2c3d51b3-0f50-4d00-925e-e48c5566e17");
        modelMine.setModelNote("请输入描述");
        modelMine.setUserType(id + "");

        modelMineRepository.save(modelMine);


    }

    @Override
    public ModelMine updateModelMine(ModelMine modelMine) {
        return modelMineRepository.save(modelMine);
    }

    @Override
    public void deleteModelMineByModelId(String modelId) {
        modelMineRepository.deleteByModelId(modelId);
    }


}
